//这是12.23 16.03
package wty;

import java.sql.*;

public class Login_SQL {
    public static boolean mysql(String ID, String Passward){
        Boolean IsTrue = false;

        try {
            com.mysql.cj.jdbc.Driver mysqlDriver = new com.mysql.cj.jdbc.Driver();
            DriverManager.registerDriver(mysqlDriver);
        } catch (SQLException e) {
            e.printStackTrace();
            System.err.println("未能正常加载MySQL驱动");
        }
        // 2. 连接到数据库服务
        // jdbc的url格式：
        String url = "jdbc:mysql://localhost:3306/project";
        String username = "root";
        String password = "root";
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(
                    url,
                    username,
                    password
            );
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            System.err.println("数据库在连接期间，出现错误！");
        }

        String sql = " SELECT  ID,Password FROM users";
        Statement sqlStatement = null;
        ResultSet resultSet = null;

        try {
            sqlStatement = connection.createStatement();
            resultSet = sqlStatement.executeQuery(sql);

            String DB_ID;
            String DB_Passwrd;
            while (resultSet.next()) {
                DB_ID = resultSet.getString("ID");
                DB_Passwrd = resultSet.getString("Password");
                if(DB_ID.equals(ID) && DB_Passwrd.equals(Passward)){
                    IsTrue = true;
                    break;
                }
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
            System.err.println("执行SQL语句时，报错");
        } finally {
            try {
                if (resultSet != null) {
                    resultSet.close();
                }
                if (sqlStatement != null) {
                    sqlStatement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
                System.err.println("在执行数据库关闭动作时，出现错误！");
            }
        }


        return IsTrue;
    }
}
